/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
using PII=pair<int, int>;
class Solution {
public:
    int ans=0;
    int dfs(TreeNode *u)
    {
        int res=0, leftdeep=0, rightdeep=0;
        if(u->left) leftdeep=dfs(u->left);
        if(u->right) rightdeep=dfs(u->right);
        ans=max(ans, leftdeep+rightdeep);
        return max(leftdeep, rightdeep)+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(root==nullptr) return 0;
        dfs(root);
        return ans;
    }
};